<script setup>
  import {watch,inject,ref,reactive,provide} from 'vue'
  import { Message } from '@arco-design/web-vue'
  import sendOrder from '@/api/document/sendOrder'
  import dictHelp from "@/utils/dicthelp.js";
  import AddPage from "@/views/document/shipment/components/actions/addSendOrder.vue";
  import EditPage from "@/views/document/shipment/components/actions/SendOrderInfo.vue";
  import commonApi from '@/api/common'
  import tool from '@/utils/tool'
  import uploadConfig from '@/config/upload'
  const crudRef = ref()
  const addPage = ref()
  const span = inject('span')
  const editPage = ref()
  const record = inject('record')
  const canDownload = ref(false)
  watch(record,(newVal,oldVal)=>{
    if(newVal.id != undefined){
      console.log('刷新派送列表--'+record.value.id)
      crudRef.value.requestData()
    }
  })
  let options = reactive({
      pk: 'id',
      pageSize:100,
      autoRequest: record.value?.id > 0,
      showTools:false,
      expandSearch:false,
      formOption: {
        viewType: 'drawer',
        width: "70%",
      },
      // 右键菜单配置
      contextMenu: {
        // 是否开启右键菜单
        enabled: false,
      },
      isDbClickEdit:false,
      operationColumn: true,
      operationColumnWidth: 120,
      tablePagination:{style:{display:"none"}},
      api: sendOrder.getList,
      beforeRequest:(param)=>{
        param.shipment_id = record.value.id
        return param;
      },
      afterRequest:(data)=>{
        canDownload.value = data.length > 0
        return data
      },
      add: {
        show: false,
        api: sendOrder.save,
        auth: ['document:sendOrder:save'],
        action:()=>{
          addPage.value.onShow()
        }
      },
      see: {
        show: true,
        api: sendOrder.update,
        text: '查看',
        action: (data)=>{
          editPage.value.onShow(data,record.value.id)
        },
      },
      delete: {
        show: false,
        api: sendOrder.deletes,
        auth: ['document:sendOrder:delete'],
        realApi: sendOrder.realDeletes,
        realAuth: ['document:sendOrder:realDeletes']
      },
    })

const columns = ref([
  {
    title: "类型",
    dataIndex: "remark",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "数量",
    dataIndex: "parcel_count",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "费用",
    dataIndex: "price",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "单号",
    dataIndex: "tracking_no",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "错误信息",
    dataIndex: "error",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
  },
]);
const singleDownload = async (record) => {
    if(record.upload.id == undefined){
      Message.error('文件还未同步')
      return;  
    }
    let url = ''
    let storeMode = getStoreMode(record.upload.storage_mode)
    console.log(storeMode)
    if (storeMode !== 'LOCAL') {
      Message.info('处理中...')
      const domain = uploadConfig.storage[storeMode]
      url = domain + record.upload.url
    } else {
      //文件上传在本地则请求后端下载
      Message.info('请求服务器下载文件中...')
      url = 'system/downloadById?id=' + record.id+'&type=attachment'
    }
    const response = await commonApi.download(url, 'get')
    if (response) {
      tool.download(response, (storeMode !== 'LOCAL') ? record.upload.origin_name : '')
      Message.success('请求成功，文件开始下载')
      sendOrder.updateStatus(record.id,{status:4})
    } else {
      Message.error('文件下载失败')  
    }
  }
  const getStoreMode = (mode) => {
    return uploadConfig.storageMode[mode.toString()]
  }
  const downloadZip = async () =>{
    let response = await sendOrder.downloadZip({ids:[record.value.id]})
    let contentType = response.headers['content-type'].toLowerCase().split(';')[0];
    let disposition = response.headers['content-disposition'].split(';')[2].split('=')[1].split('\'')[2]
    saveAs(new Blob([response.data], {type: contentType}), decodeURIComponent(disposition))
  }
  const cancel = async (info)=>{
    let res = await sendOrder.cancel({id:info.id})
    if(!res.success){
      Message.error('操作失败')
      return
    }
    Message.success('操作成功')
    crudRef.value.refresh()
  }
  const synchronous = async (info)=>{
    let res = await sendOrder.synchronous({id:info.id})
    if(!res.success){
      Message.error('操作失败')
      return
    }
    Message.success('操作成功')
    crudRef.value.refresh()
  }
provide('crudRef',crudRef)
</script>
<script>
export default { name: 'document:sendOrder' }
</script>

<template>
  <a-grid-item :span="span">
    <a-collapse :default-active-key="['1']" class="g-collapse-no-p">
      <a-collapse-item header="派送" key="1">
        <template #extra>
          <a-button-group>
            <a-button type="primary" size="mini" @click.stop="crudRef.refresh()" v-auth="['document:sendOrder:save']">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
            <a-button type="primary" size="mini" @click.stop="crudRef.addAction()" v-auth="['document:sendOrder:save']">
              <template #icon><icon-plus /></template>
              {{ record.merge_id > 0 ? '合并新增' : '新增'}} 
            </a-button>
            <a-button v-if="canDownload" type="primary" size="mini" @click.stop="downloadZip()" v-auth="['document:sendOrder:download']">
              <template #icon>
                <icon-download />
              </template>
              下载
            </a-button>
          </a-button-group>
        </template>
          <ma-crud :options="options" :columns="columns" ref="crudRef" class="file-list">
            <template #operationBeforeExtend="{ record }">
              <a-link v-if="record.url" title="下载" v-auth="['document:sendOrder:download']" @click="singleDownload(record)">
                <template #icon>
                  <icon-download />
                </template>
                下载
              </a-link>
              <a-popconfirm v-else 
                        content="确定要同步吗?"
                        position="bottom"
                        @click.stop=""
                        @ok="synchronous(record)"
                    >
                <a-link  title="同步" v-auth="['document:sendOrder:synchronous']">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  同步
                </a-link>
              </a-popconfirm>

              <a-popconfirm v-if="record.cancel == 0" 
                        content="确定要作废吗?"
                        position="bottom"
                        @click.stop=""
                        @ok="cancel(record)"
                    >
                <a-link title="作废" v-auth="['document:sendOrder:cancel']">
                  <template #icon>
                    <icon-close />
                  </template>
                  作废
                </a-link>
              </a-popconfirm>
              <span v-else>已作废</span>
            </template>
          </ma-crud>
          <add-page ref="addPage" />
          <edit-page ref="editPage" />
      </a-collapse-item>
    </a-collapse>
  </a-grid-item>
</template>
<style>
.file-list ._crud-header,.file-list .mb-2,.file-list .operation-tools,.file-list .mb-1{
  display:none;
}

</style>